﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;

namespace WebComTest.WebUI.Models.RequestManagers
{
    public class SoapRequest
    {
        private string url { get; set; }

        public SoapRequest(string url)
        {
            this.url = url;
        }

        public string CallWebService(string action, string soapMessage)
        {
            string soapResult;

            HttpWebRequest webRequest = CreateWebRequest(this.url, action);
            webRequest.InsertSoapEnvelope(CreateSoapEnvelope(soapMessage));
            using (WebResponse webResponse = webRequest.GetResponse())
            {
                using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
                {
                    soapResult = rd.ReadToEnd();
                }
            }

            return soapResult;
        }

        private HttpWebRequest CreateWebRequest(string url, string action)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Headers.Add("SOAPAction", action);
            webRequest.ContentType = "text/xml;charset=\"utf-8\"";
            webRequest.Accept = "text/xml";
            webRequest.Method = "POST";
            return webRequest;
        }

        private XmlDocument CreateSoapEnvelope(string soapMessage)
        {
            XmlDocument soapEnvelop = new XmlDocument();
            soapEnvelop.LoadXml(soapMessage);
            return soapEnvelop;
        }
    }
}